package com.sunny.service;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.sunny.dao.ApiMetaNameDao;
import com.sunny.dao.ApiMetaParamDao;
import com.sunny.dao.ApiMetaResultDao;
import com.sunny.entity.ApiMetaNameEntity;
import com.sunny.entity.ApiMetaParamEntity;
import com.sunny.entity.ApiMetaResultEntity;
import com.sunny.common.pojo.SunResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Statement;
import java.util.List;

@Service
@Slf4j
public class FinanceService {
    @Autowired
    private ApiMetaNameDao metaNameDao;
    @Autowired
    private ApiMetaParamDao paramDao;
    @Autowired
    private ApiMetaResultDao resultDao;
    @Autowired
    DruidDataSource druidDataSource;

    public SunResult addMetaName(ApiMetaNameEntity nameEntity) {
        metaNameDao.save(nameEntity);
        return SunResult.ok();
    }

    public SunResult addMetaParam(List<ApiMetaParamEntity> paramEntitys) {
        paramDao.saveAll(paramEntitys);
        return SunResult.ok();
    }

    public SunResult addMetaResult(List<ApiMetaResultEntity> resultEntitys) {
        resultDao.saveAll(resultEntitys);
        return SunResult.ok();
    }

    /**
     * 基于元数据创建表
     */
    public SunResult createFinanceTables() {
        List<ApiMetaNameEntity> mNameList = metaNameDao.findAll();
        log.info("创建表数量：" + mNameList.size());
        mNameList.forEach(t->{
            String[] ddls = genCreateTableScript(t);
            doCreateTable(ddls);
        });
        log.info("建表完毕");
        return SunResult.ok("建表完毕");
    }

    private String[] genCreateTableScript(ApiMetaNameEntity entity) {
        //查询字段列表
        List<ApiMetaResultEntity> colList = resultDao.findByApiId(entity.getApiId());
        //创建表名
        String tableName = "f_" + entity.getApiCode();
        String[] ddls = new String[2];
        ddls[0] = "drop table if exists " + tableName + ";";
        StringBuilder sb = new StringBuilder();
        sb.append("CREATE TABLE " + tableName + "(");
        sb.append("  tid bigint NOT NULL,");
        colList.forEach(c->{
            sb.append("  `" + c.getResName() + "` ");
            String comment = c.getResDesc();
            if (StringUtils.isNotBlank(comment)) {
                //去掉字符串中的单引号
                comment = comment.replace("'", "");
            } else {
                comment = "";
            }
            if ("str".equals(c.getResType())) {
                sb.append("varchar(30) COMMENT '" + comment + "',");
            } else if ("float".equals(c.getResType())) {
                sb.append("float COMMENT '" + comment + "',");
            } else if ("int".equals(c.getResType())) {
                sb.append("int COMMENT '" + comment + "',");
            }
        });
        sb.append("  PRIMARY KEY (tid) USING BTREE");
        sb.append(") ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='" + entity.getApiName() + "';");
        ddls[1] = sb.toString();
        return ddls;
    }

    private void doCreateTable(String[] ddls) {
        log.info("建表语句：{}", ddls[1]);
        int result = 0;
        try {
            DruidPooledConnection connection = druidDataSource.getConnection();
            Statement statement = connection.createStatement();
            statement.executeUpdate(ddls[0]);
            statement.executeUpdate(ddls[1]);
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("创建表失败：{}", e.getMessage());
        }
    }


}
